package com.example.demo.leetcode.top100;

import java.util.*;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _41二叉树的层序遍历
 * @description
 * @date 2023/06/15 22:09
 * <p>
 * ******************************************************
 */
public class _41二叉树的层序遍历 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
//        List<Integer> rootList = new LinkedList<>();

        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> item = new LinkedList<>();
            List<TreeNode> itemQueue = new LinkedList<>();
            final Iterator<TreeNode> iterator = queue.iterator();
            while (iterator.hasNext()) {
                TreeNode treeNode = iterator.next();
                item.add(treeNode.val);
                if (treeNode.left != null) {
                    itemQueue.add(treeNode.left);
                }
                if (treeNode.right != null) {
                    itemQueue.add(treeNode.right);
                }
                iterator.remove();
            }
            result.add(item);
            for (TreeNode treeNode : itemQueue) {
                queue.offer(treeNode);
            }


        }
        return result;
    }

    public static void main(String[] args) {
        _41二叉树的层序遍历 s = new _41二叉树的层序遍历();
        TreeNode a = new TreeNode(15);
        TreeNode b = new TreeNode(7);
        TreeNode c = new TreeNode(20, a, b);
        TreeNode d = new TreeNode(9);
        TreeNode e = new TreeNode(1, d,c);
        s.levelOrder(e);
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
